<script lang="ts" setup>
import { reactive, ref, onMounted, computed } from "vue";
import {
  getBillPage,
  getDetailBill,
  updateBillInfo,
  statementOfAccount
} from "/@/api/bill";
import dayjs from "dayjs";
import { exportPdf } from "/@/utils";
import { ElMessage } from "element-plus";
import NP from "number-precision";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
dayjs.extend(utc);
dayjs.extend(timezone);

defineOptions({
  name: "BillIndex"
});

onMounted(() => {
  getTableData();
});

const tableData = ref([]);
const query = reactive({
  container_no: "",
  bill_of_lading: "",
  user_name: "",
  currentPage: 1,
  pageSize: 15
});
const total = ref(0);
const dialogVisible = ref<boolean>(false);
const detailData = ref<any>({});
const showInvoice = ref(false);
const showDate = ref(false);
const showTerms = ref(false);
const showDueDate = ref(false);
const showQuantity = ref(false);
const showRate = ref(false);
const inputWidth = "165px";
const index = ref(-1);
const rateIndex = ref(-1);
const allTotal = computed(() => {
  return detailData.value.bill.reduce((pre, item) => {
    return NP.plus(pre, item.amount);
  }, 0);
});
const role = JSON.parse(localStorage.getItem("authorized-token")).role;
const isUser = role === "user";

const getTableData = () => {
  getBillPage(query).then((res: any) => {
    tableData.value = res.data.data;
    total.value = res.data.total;
  });
};

const handleSizeChange = val => {
  query.pageSize = val;
  getTableData();
};

const handleCurrentChange = val => {
  query.currentPage = val;
  getTableData();
};

const goDetail = val => {
  getDetailBill({ child_identifier: val.child_identifier }).then(({ data }) => {
    detailData.value = data;
    dialogVisible.value = true;
  });
};

const exportPdfHandle = () => {
  exportPdf(".el-dialog__body", "账单详情");
};

const invoiceMouseleave = () => {
  if (isUser) return;
  showInvoice.value = false;
};
const invoiceMouseenterHandle = () => {
  if (isUser) return;
  showInvoice.value = true;
};
const dateMouseleave = () => {
  if (isUser) return;
  showDate.value = false;
};
const dateMouseenterHandle = () => {
  if (isUser) return;
  showDate.value = true;
};
const termsMouseleave = () => {
  if (isUser) return;
  showTerms.value = false;
};
const termsMouseenterHandle = () => {
  if (isUser) return;
  showTerms.value = true;
};
const dueDateMouseleave = () => {
  if (isUser) return;
  showDueDate.value = false;
};
const dueDateMouseenterHandle = () => {
  if (isUser) return;
  showDueDate.value = true;
};
const quantityMouseleave = () => {
  if (isUser) return;
  showQuantity.value = false;
};
const quantityMouseenterHandle = i => {
  if (isUser) return;
  index.value = i;
  showQuantity.value = true;
};
const rateMouseleave = () => {
  if (isUser) return;
  showRate.value = false;
};
const rateMouseenterHandle = i => {
  if (isUser) return;
  rateIndex.value = i;
  showRate.value = true;
};

const updataInfo = () => {
  const { child_identifier, invoice, date, terms, due_date } = detailData.value;
  const bills = detailData.value.bill.map(item => {
    return {
      id: item.id,
      quantity: item.quantity,
      rate: item.rate
    };
  });
  const obj = { child_identifier, invoice, date, terms, due_date, bills };
  updateBillInfo(obj).then(() => {
    ElMessage({
      type: "success",
      message: "更新成功"
    });
    dialogVisible.value = false;
  });
};

const confirm = ({ child_identifier, user_nid }) => {
  statementOfAccount({ child_identifier, user_nid }).then(() => {
    ElMessage({
      type: "success",
      message: "操作成功"
    });
    getTableData();
  });
};

const filterType = val => {
  let str = "";
  switch (val) {
    case 1:
      str = "提柜";
      break;
    case 2:
      str = "中转";
      break;
    case 3:
      str = "退件";
      break;
  }
  return str;
};

const setTotal = (val, i) => {
  const quantity = val === "" ? 0 : Number(val);
  const rate = Number(detailData.value.bill[i].rate);
  detailData.value.bill[i].amount = NP.times(quantity, rate).toFixed(2);
};

const setTotalForRate = (val, i) => {
  const rate = val === "" ? 0 : Number(val);
  const quantity = Number(detailData.value.bill[i].quantity);
  detailData.value.bill[i].amount = NP.times(quantity, rate).toFixed(2);
};
</script>

<template>
  <div class="bill-list">
    <el-card>
      <!-- search start -->
      <el-form :inline="true" :model="query" label-width="auto">
        <el-form-item label="客户:">
          <el-input v-model="query.user_name" />
        </el-form-item>
        <el-form-item label="柜号:">
          <el-input v-model="query.container_no" />
        </el-form-item>
        <el-form-item label="提单号:">
          <el-input v-model="query.bill_of_lading" />
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" @click="getTableData">搜 索</el-button>
        </el-form-item>
      </el-form>
      <!-- search end -->
      <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="identifier" label="编号" />
        <el-table-column prop="user_name" label="客户" />
        <el-table-column prop="container_no" label="柜号" />
        <el-table-column prop="bill_of_lading" label="提单号" />
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">
            <div>
              {{ filterType(row.type) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="服务名称" />
        <el-table-column prop="total_amount" label="费用" />
        <el-table-column label="创建时间(加利福尼亚)">
          <template #default="{ row }">
            {{
              row.created_at
                ? dayjs(row.created_at * 1000)
                    .tz("America/Los_Angeles")
                    .format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间(加利福尼亚)">
          <template #default="{ row }">
            {{
              row.updated_at
                ? dayjs(row.updated_at * 1000)
                    .tz("America/Los_Angeles")
                    .format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="{ row }">
            <el-button type="primary" @click="goDetail(row)"
              >查看详细账单</el-button
            >
            <el-button
              type="primary"
              v-if="row.is_statement_of_account == 0"
              @click="confirm(row)"
              >确 认</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-pagination
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          :page-sizes="[5, 10, 15, 20, 30]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="Number(total)"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" width="50%">
      <span>
        <div style="color: #000; font-weight: 900">
          Cena Mae Logistics Solution Inc.
        </div>
        <div style="font-size: 12px">2059 California Ave</div>
        <div style="font-size: 12px">Corona, CA 92881 US</div>
        <div style="font-size: 12px">cenamaefinancial@gmail.com</div>
        <div class="INVOICE">INVOICE</div>
        <div class="info">
          <div class="left">
            <div class="title">BILL TO</div>
            <div>{{ detailData.name }}</div>
            <div>{{ detailData.company_name }}</div>
            <div>{{ detailData.company_address }}</div>
          </div>
          <div class="right">
            <el-form
              :model="detailData"
              label-width="75px"
              size="small"
              label-position="left"
            >
              <el-form-item label="INVOICE">
                <el-input
                  @mouseleave="invoiceMouseleave"
                  v-show="showInvoice"
                  v-model="detailData.invoice"
                  :style="{ width: inputWidth }"
                />
                <div
                  v-show="!showInvoice"
                  class="form-row"
                  @mouseenter="invoiceMouseenterHandle"
                >
                  {{ detailData.invoice }}
                </div>
              </el-form-item>
              <el-form-item label="DATE">
                <div @mouseleave="dateMouseleave" v-show="showDate">
                  <!-- <el-date-picker
                    v-model="detailData.date"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :style="{ width: inputWidth }"
                  /> -->
                  <el-input
                    v-model="detailData.date"
                    :style="{ width: inputWidth }"
                    placeholder="以xxxx-xx-xx格式"
                  />
                </div>
                <div
                  v-show="!showDate"
                  class="form-row"
                  @mouseenter="dateMouseenterHandle"
                >
                  {{ detailData.date }}
                </div>
              </el-form-item>
              <el-form-item label="TERMS">
                <el-input
                  @mouseleave="termsMouseleave"
                  v-show="showTerms"
                  v-model="detailData.terms"
                  :style="{ width: inputWidth }"
                />
                <div
                  v-show="!showTerms"
                  class="form-row"
                  @mouseenter="termsMouseenterHandle"
                >
                  {{ detailData.terms }}
                </div>
              </el-form-item>
              <el-form-item label="DUE DATE">
                <div @mouseleave="dueDateMouseleave" v-show="showDueDate">
                  <!-- <el-date-picker
                    v-model="detailData.due_date"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :style="{ width: inputWidth }"
                  /> -->
                  <el-input
                    v-model="detailData.due_date"
                    :style="{ width: inputWidth }"
                    placeholder="以xxxx-xx-xx格式"
                  />
                </div>
                <div
                  v-show="!showDueDate"
                  class="form-row"
                  @mouseenter="dueDateMouseenterHandle"
                >
                  {{ detailData.due_date }}
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="content">
          <el-row class="row-base" style="background: #dfeaf0">
            <el-col :span="6" style="color: #527896; padding-left: 5px"
              >ACTIVITY</el-col
            >
            <el-col :span="9" style="color: #527896">DESCRIPTION</el-col>
            <el-col :span="2" class="ta-r" style="color: #527896">QIY</el-col>
            <el-col :span="3" class="ta-r" style="color: #527896">RATE</el-col>
            <el-col
              :span="4"
              class="ta-r"
              style="color: #527896; padding-right: 5px"
              >AMOUNT</el-col
            >
          </el-row>

          <el-row
            class="row-base"
            v-for="(item, i) in detailData.bill"
            :key="i"
          >
            <el-col :span="6" style="padding-left: 5px">{{ item.name }}</el-col>
            <el-col :span="9">{{ item.description }}</el-col>
            <el-col :span="2" class="ta-r">
              <el-input
                @mouseleave="quantityMouseleave"
                v-show="showQuantity && index === i"
                v-model="detailData.bill[i].quantity"
                @input="val => setTotal(val, i)"
                :style="{ width: '100px' }"
                size="small"
              />
              <div
                v-show="index === i ? !showQuantity : true"
                class="form-row"
                @mouseenter="quantityMouseenterHandle(i)"
              >
                {{ item.quantity }}
              </div>
            </el-col>
            <el-col :span="3" class="ta-r">
              <el-input
                @mouseleave="rateMouseleave"
                v-show="showRate && rateIndex === i"
                v-model="detailData.bill[i].rate"
                @input="val => setTotalForRate(val, i)"
                :style="{ width: '100px' }"
                size="small"
              />
              <div
                v-show="rateIndex === i ? !showRate : true"
                class="form-row"
                @mouseenter="rateMouseenterHandle(i)"
              >
                {{ item.rate }}
              </div>
            </el-col>
            <el-col :span="4" class="ta-r" style="padding-right: 5px">{{
              item.amount
            }}</el-col>
          </el-row>

          <div class="line" />
        </div>
        <div class="footer">
          <div />
          <div>Balance Due</div>
          <div>${{ allTotal }}</div>
        </div>
      </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="exportPdfHandle">
            导出pdf
          </el-button>
          <el-button
            type="primary"
            @click="updataInfo"
            v-auth="['admin', 'super', 'warehouse']"
          >
            更新账单信息
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
::v-deep(.el-form-item--small) {
  margin-bottom: 5px;

  label {
    color: #848484 !important;
  }
}
::v-deep(.el-dialog__header) {
  padding: 0 !important;
}

.ta-r {
  text-align: right;
}

::v-deep(.row-base, .row) {
  height: 30px;
  line-height: 30px;
}

.INVOICE {
  font-size: 16px;
  color: #527896;
}

.info {
  display: flex;
  justify-content: space-between;

  .left {
    div {
      margin-top: 5px;
    }
    .title {
      margin-top: 0px;
      color: #848484;
    }
  }

  .right {
    margin-right: 80px;

    .form-row {
      width: 170px;
      height: 100%;
    }
  }
}

.content {
  margin-top: 40px;

  .line {
    margin-top: 10px;
    width: 100%;
    height: 0.5px;
    border-top: 1px dashed #dddddd;
  }
}

.footer {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;

  div {
    color: #848484;

    &:nth-child(1) {
      font-size: 12px;
    }

    &:nth-child(3) {
      color: #000;
      font-weight: 900;
    }
  }
}
</style>
